// src/hooks/use-confirm.tsx
import React, {JSX, useState} from 'react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader, DialogTitle,
    DialogTrigger
} from "@/components/ui/dialog";
import {Button} from "@/components/ui/button";

const UseConfirm = (
    title: string,
    message: string,
): [() => JSX.Element, () => Promise<unknown>] => {
    // 这种设计可以const ok = await confirm() -> if(!ok) ...
    const [promise, setPromise] =
        useState<{ resolve: (value: boolean) => void } | null>(null);

    const confirm = () => new Promise((resolve, reject) => {
        setPromise({resolve})
    })

    const handleClose = () => {
        setPromise(null)
    }

    const handleCancel = () => {
        promise?.resolve(false)
        handleClose()
    }

    const handleConfirm = () => {
        promise?.resolve(true)
        handleCancel()
    }

    const ConfirmDialog = () => <Dialog open={promise !== null}>
        <DialogContent>
            <DialogHeader>
                <DialogTitle>
                    {title}
                </DialogTitle>
                <DialogDescription>
                    {message}
                </DialogDescription>
            </DialogHeader>
            <DialogFooter className={`pt-2`}>
                <Button
                    onClick={handleConfirm}
                >
                    Confirm
                </Button>
                <Button
                    onClick={handleCancel}
                    variant={"outline"}
                >
                    Cancel
                </Button>
            </DialogFooter>
        </DialogContent>
    </Dialog>

    return [ConfirmDialog, confirm]
};

export default UseConfirm;